# encoding:utf-8
import sys
from app.utils.account import get_current_user
from flask import Flask, render_template, g
from flask.ext.bootstrap import Bootstrap
from config import config


# convert python's encoding to utf8
reload(sys)
sys.setdefaultencoding('utf8')

bootstrap = Bootstrap()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap.init_app(app)

    # 注册Model
    from .models.base import db
    db.init_app(app)

    # 注册路由
    from app.views.employee import employee_pages
    app.register_blueprint(employee_pages, url_prefix="/admin")

    # 注册错误处理
    @app.errorhandler(403)
    def page_403(error):
        return render_template('403.html'), 403

    @app.errorhandler(404)
    def page_404(error):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def page_500(error):
        return render_template('500.html'), 500

    @app.before_request
    def before_request():
        g.user = get_current_user()

    @app.after_request
    def after_request(response):

        return response
    return app
